<template>
  <div class="container-box">
    <!-- 弹窗 -->
    <el-dialog v-model="store.questionInsertOpen" :show-close="false" append-to-body class="dialogClass" width="60%" top="30px" draggable overflow >
      <!--弹窗标题-->
      <template #header="{ close, titleId }">
        <div class="dialogHeader">
          <span :id="titleId" class="dlgTitleClass" style="margin: 10px 10px;" v-if="store.questionId===0&&!isNaN(store.questionId)">新增</span>
          <span :id="titleId" class="dlgTitleClass" style="margin: 10px 10px; " v-if="store.questionId!==0&&!isNaN(store.questionId)">修改</span>
          <el-icon style="font-size: 16px;margin-top: 14px;cursor: pointer" @click="closeDialog()">
            <CloseBold/>
          </el-icon>
        </div>
      </template>
      <div style="max-height: 600px; overflow-y: auto;">
        <el-form :model="form" label-width="120px" :rules="rules" ref="formRef">
          <!-- 题库 -->
          <el-form-item label="题库" prop="bankId">
            <el-select v-model="form.bankId" placeholder="请选择题库">
              <el-option v-for="item in bankList" :key="item.key" :label="item.value" :value="item.key" />
            </el-select>
          </el-form-item>
          <!-- 题目 -->
          <el-form-item label="题目内容" prop="content">
            <RichTextEditor v-model:get-html="form.content" :height="'200px'" placeholder="请输入题目内容" />
          </el-form-item>

          <!-- 题目类型 -->
          <el-form-item label="题目类型" prop="type">
            <el-select v-model="form.type" placeholder="请选择题目类型" @change="handleTypeChange">
              <el-option label="单选题" value="single"></el-option>
              <el-option label="多选题" value="multiple"></el-option>
              <el-option label="判断题" value="judgment"></el-option>
              <el-option label="填空题" value="fill"></el-option>
              <el-option label="简答题" value="essay"></el-option>
            </el-select>
          </el-form-item>

          <!-- 单选、多选题选项 -->
          <el-form-item
              v-if="['single', 'multiple'].includes(form.type)"
              label="选项"
              prop="options"
          >
            <!-- 添加选项按钮 -->
            <div style="max-height: 300px;overflow-y: auto;margin-right: 20px;">
              <el-button type="primary" class="el-button__primary" style="margin-bottom: 20px;" @click="addOption">添加选项</el-button>
              <!-- 选项列表 -->
              <div v-for="(option, index) in form.options" :key="index" class="option-item">
                <span style="margin-right: 10px; font-weight: bold;">{{ String.fromCharCode(65 + index) }}:</span>
                <RichTextEditor v-model:get-html="option.value" :height="'150px'" />
                <el-button style="margin-left: 20px" class="el-button__plain" @click="removeOption(index)">删除</el-button>
              </div>
            </div>

          </el-form-item>

          <!-- 判断题选项 -->
          <el-form-item
              v-else-if="form.type === 'judgment'"
              label="选项"
              prop="options"
              class="el-form-item--judgment"
          >
            <div v-for="(option, index) in form.options" :key="index" class="option-item">
              <span>{{ option.key }}:</span>
              <span>{{ option.value }}</span>
            </div>
          </el-form-item>

          <!-- 解析 -->
          <el-form-item label="题目解析" prop="explanation">
            <RichTextEditor v-model:get-html="form.explanation" :height="'200px'" />
          </el-form-item>

          <!-- 答案 -->
          <el-form-item label="答案" prop="answer">
            <el-input v-model="form.answer" placeholder="请输入答案" />
          </el-form-item>

          <!-- 提交按钮 -->
          <el-form-item style="float: right;margin-right: 20px">
            <el-button type="primary" @click="submitForm"  v-if="store.questionId===0" class="el-button__primary">提交</el-button>
            <el-button type="primary" @click="updateQuestion"  v-if="store.questionId!==0" class="el-button__primary">修改</el-button>
            <el-button @click="resetForm" class="el-button__default">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

    </el-dialog>

  </div>
</template>

<script setup lang="ts">
import {defineEmits, onMounted, reactive, ref, watch} from "vue";
import RichTextEditor from "../..//components/RichTextEditor.vue";
import {CloseBold} from "@element-plus/icons-vue";
import {questionStore} from "@/stores/question/questionStore.ts";
import {ElMessage, ElMessageBox} from "element-plus";
import {getBankList, updateBank} from "@/api/question/bank.ts";
import {addQuestion, getQuestionById, updateQuestionInfo} from "@/api/question/question.ts";
const store=questionStore()
const emit = defineEmits(['refresh'])
const bankList=ref([])
onMounted(()=>{
  initBankList()
})
const closeDialog=()=>{
  resetForm()
  store.setQuestionInsertOpen(false)
  store.setQuestionId(0)
  emit("refresh")
}
// 表单数据
const form = reactive({
  id:0,
  bankId:null,
  content: "", // 题目
  answer: "", // 答案
  explanation: "", // 解析
  type: "", // 题目类型
  options: [] as { key: string; value: string }[], // 选项
});

// 表单校验规则
const rules = {
  bankId: [{ required: true, message: "请选择题库", trigger: "blur" }],
  content: [{ required: true, message: "请输入题目", trigger: "blur" }],
  answer: [{ required: true, message: "请输入答案", trigger: "blur" }],
  type: [{ required: true, message: "请选择题目类型", trigger: "change" }],
};

// 表单引用
const formRef = ref();

watch(store,async () => {
  if (store.questionId !== 0) {
   const  res=await getQuestionById(store.questionId)
    form.id=res.data.id
    form.bankId=res.data.bankId
    form.content = res.data.content;
    form.answer = res.data.answer;
    form.explanation = res.data.explanation;
    form.type = res.data.questionType;
    form.options = res.data.options;
  }
})
// 添加选项
const addOption = () => {
  const key = String.fromCharCode(65 + form.options.length); // 动态生成 A, B, C...
  form.options.push({ key, value: "" });
};
const initBankList=async () => {
  const res = await getBankList()
  bankList.value = res.data
}
// 删除选项
const removeOption = (index: number) => {
  form.options.splice(index, 1);
};
const updateQuestion=()=>{
  formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      if ((form.type === "single" || form.type === "multiple") && form.options.length === 0) {
        ElMessage.error("单选题或多选题必须添加选项");
      }else {
        const data={
          id:form.id,
          bankId:form.bankId,
          content:form.content,
          answer: form.answer,
          options: form.options,
          questionType:form.type,
          explanation:form.explanation
        }
        ElMessageBox.confirm(
            '确定修改试题信息?',
            '提示', {
              app: undefined, components: undefined, config: undefined, directives: undefined, mixins: [], provides: undefined,
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }
        ).then(async () => {
          const res = await updateQuestionInfo(data);
          if (res){
            ElMessage.success("修改成功");
            resetForm();
            store.setQuestionInsertOpen(false)
            emit("refresh")
          }
        }).catch(() => {
        })
      }
    }
  });

}
// 题目类型切换时处理
const handleTypeChange = () => {
  // 清空选项
  form.options = [];
  if (form.type === "judgment") {
    // 判断题默认选项为 true 和 false
    form.options = [
      { key: "A", value: "正确" },
      { key: "B", value: "错误" },
    ];
  } else if (!["single", "multiple"].includes(form.type)) {
    // 其他类型清空选项
    form.options = [];
  }
};

// 提交表单
const submitForm = () => {
  formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      if ((form.type === "single" || form.type === "multiple") && form.options.length === 0) {
        ElMessage.error("单选题或多选题必须添加选项");
      }
      const data={
        bankId:form.bankId,
        content:form.content,
        answer: form.answer,
        options: form.options,
        questionType:form.type,
        explanation:form.explanation
      }
      const res = await addQuestion(data);
      if (res){
        ElMessage.success("添加成功");
        resetForm();
        store.setQuestionInsertOpen(false)
        emit("refresh")
      }
    }
  });
};

// 重置表单
const resetForm = () => {
  formRef.value.resetFields();
};
</script>

<style scoped>
/* 确保“添加选项”按钮单独占一行 */
.el-form-item > div:first-child {
  display: block;
}

/* 选项项的样式 */
.option-item {
  display: flex;
  align-items: flex-start; /* 顶部对齐 */
  margin-bottom: 10px; /* 调整项之间的间距 */
}

/* 选项标签（如 A:, B:）的样式 */
.option-item span:first-child {
  font-weight: bold;
  margin-right: 5px; /* 调整键（A, B等）与值之间的间距 */
}

/* 删除按钮的样式 */
.option-item .el-button {
  margin-top: 10px; /* 删除按钮与编辑器顶部对齐 */
}

/* 其他通用样式 */
.el-select,
.el-input {
  width: 160px;
}
.dialogClass{
  .el-dialog__body{
    min-height: 300px;
    max-height: 600px;
    overflow: auto;
  }
}
/* 确保对话框主体可以使用flex布局 */
:deep(.el-dialog__body) {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
  padding: 0 50px!important;
}
/* 统一选择框、数字框和输入框的宽度 */
.el-input,
.el-input-number,
.el-select,
.el-tree-select{
  --el-select-input-focus-border-color: rgb(46, 92, 246);
  --el-color-primary: rgb(46, 92, 246);
  box-sizing: border-box; /* 确保内边距和边框包含在元素的总宽度和高度内 */
}

.el-radio.is-bordered.is-checked {
  --el-color-primary: rgb(46, 92, 246);
}

.el-radio {
  --el-radio-input-border-color-hover: rgb(46, 92, 246);
}
.el-dialog .el-dialog__header {
  margin: 0 !important;
  padding: 0 !important;
}

.el-dialog .dialogHeader {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  height: 40px;
  margin: 0 10px;
  font-size: 18px;
  font-weight: bolder;
}

</style>